﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewResourceObjectAndDevice : Form
    {
        public fmNewResourceObjectAndDevice()
        {
            InitializeComponent();
        }

        private void fmNewResourceObjectAndDevice_Load(object sender, EventArgs e)
        {
            DataTable dtPushType = new DataTable();
            dtPushType.Columns.Add("VALUE", typeof(string));
            dtPushType.Columns.Add("TEXT", typeof(string));
            dtPushType.Rows.Add(new object[] { "0", "不向资源表推送" });
            dtPushType.Rows.Add(new object[] { "1", "华云" });
            dtPushType.Rows.Add(new object[] { "2", "总平台" });
            dtPushType.Rows.Add(new object[] { "3", "都需要" });

            this.cbxPushType.ValueMember = "VALUE";
            this.cbxPushType.DisplayMember = "TEXT";
            this.cbxPushType.DataSource = dtPushType;
            this.cbxPushType.SelectedIndex = 0;

            DataTable dtResourceType = new DataTable();
            dtResourceType.Columns.Add("VALUE", typeof(string));
            dtResourceType.Columns.Add("TEXT", typeof(string));
            dtResourceType.Rows.Add(new object[] { "", "" });


            this.cbxResourceType.ValueMember = "VALUE";
            this.cbxResourceType.DisplayMember = "TEXT";
            this.cbxResourceType.DataSource = dtResourceType;
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {
            DataTable dtSite = SiteBindingSource.DataSource as DataTable;
            if (dtSite == null || !dtSite.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }


            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            var drSite = dtA.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");

            // 判断右侧资源对象是否有勾选
            DataTable dtResource = ResourceBindingSource.DataSource as DataTable;
            bool hasResourceSelected = dtResource != null && dtResource.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True");
            int isDel = 1;
            fmNewObjectDevice.ResourceObjectInfo resourceObjectInfo = null;
            if (!hasResourceSelected)
            {
                if (string.IsNullOrWhiteSpace(cbxResourceType.Text))
                {
                    MessageBox.Show("请选择自定义资源类型");
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtPtDate.Text) || string.IsNullOrWhiteSpace(txtWhDate.Text))
                {
                    MessageBox.Show("更新时间不可为空！");
                    return;
                }
                string format = "yyyyMMdd";
                if (!DateTime.TryParseExact(txtPtDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime PtDate))
                {
                    MessageBox.Show("功率更新时间的时间格式错误！");
                    return;
                }
                if (!DateTime.TryParseExact(txtWhDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime WhDate))
                {
                    MessageBox.Show("电量更新时间的时间格式错误！");
                    return;
                }
                if (cbOn.Checked)
                {
                    isDel = 0;
                }
                // 组装资源对象参数
                resourceObjectInfo = new fmNewObjectDevice.ResourceObjectInfo
                {
                    FactoryStationId = drSite["ID"].ToString(),
                    Name = drSite["NAME"].ToString(),
                    CustomNo = txtCustomNo.Text,
                    ResourceTypeId = cbxResourceType.SelectedValue?.ToString(),
                    ParentFactoryStationId = txtParentID.Text,
                    RangeType = drSite["CLASSNAME"].ToString() == "Filiale" ? 0 : 1,
                    IsDel = isDel,
                    PushType = cbxPushType.SelectedValue?.ToString(),
                    PtDate = txtPtDate.Text,
                    WhDate = txtWhDate.Text
                };
                // 判断资源对象是否已存在
                var dtResourceObject = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id FROM custom_resource_object WHERE custom_resource_type_id={MySQLHelper.ConvertGuidToSql(resourceObjectInfo.ResourceTypeId)} and factory_station_id={MySQLHelper.ConvertGuidToSql(resourceObjectInfo.FactoryStationId)} and custom_no {MySQLHelper.ConvertGuidToSelectSql(resourceObjectInfo.CustomNo)}");
                if (dtResourceObject != null && dtResourceObject.Rows.Count > 0)
                {
                    MessageBox.Show($@"站点已存在该资源类型的资源对象！");
                    return;
                }
            }
            else
            {
                //已勾选资源对象情况下用查询数据的方式获取资源对象信息赋值resourceObjectInfo
                var drResource = dtResource.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");

                resourceObjectInfo = new fmNewObjectDevice.ResourceObjectInfo
                {
                    Id = drResource["id"].ToString(),
                    FactoryStationId = drResource["factory_station_id"].ToString(),
                    Name = drResource["fname"].ToString(),
                    CustomNo = drResource["custom_no"].ToString(),
                    ResourceTypeId = drResource["custom_resource_type_id"].ToString(),
                    ParentFactoryStationId = drResource["parent_factory_station_id"].ToString(),
                    RangeType = drResource["range_type"] != DBNull.Value ? Convert.ToInt32(drResource["range_type"]) : 0,
                    IsDel = drResource["deleted"] != DBNull.Value ? Convert.ToInt32(drResource["deleted"]) : 0,
                    PushType = drResource["push_type"].ToString(),
                    PtDate = drResource["PtDate"].ToString(),
                    WhDate = drResource["WhDate"].ToString()
                };
            }

            resourceObjectInfo.dtPushType = this.cbxPushType.DataSource as DataTable;
            resourceObjectInfo.dtResourceType = this.cbxResourceType.DataSource as DataTable;


            // 打开设备选择窗口并传递参数
            var dlg = new fmNewObjectDevice();
            dlg.ResourceObjectParams = resourceObjectInfo;
            dlg.ShowDialog();

            var drv = DeviceBindingSource.Current as DataRowView;
            if (drv == null)
            {
                return;
            }
            {
                var dtAR = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"
SELECT
	custom_resource_object.id,
	custom_resource_object.factory_station_id,
	custom_resource_object.fname,
	custom_resource_type.type_name,
	custom_resource_object.parent_factory_station_id,
	custom_resource_object.custom_no,
	custom_resource_object.range_type,
	custom_resource_object.custom_resource_type_id,
	custom_resource_object.deleted,
	custom_resource_object.push_type,
	(
SELECT REPLACE
	( CAST( update_day AS DATE ), '-', '' ) 
FROM
	custom_object_value_type_time 
WHERE
	custom_object_value_type_time.custom_resource_object_id = custom_resource_object.id 
	AND custom_object_value_type_time.data_value_type = 0 
	) AS PtDate,
	(
SELECT REPLACE
	( CAST( update_day AS DATE ), '-', '' ) 
FROM
	custom_object_value_type_time 
WHERE
	custom_object_value_type_time.custom_resource_object_id = custom_resource_object.id 
	AND custom_object_value_type_time.data_value_type = 1 
	) AS WhDate 
FROM
	custom_resource_object
	LEFT JOIN custom_resource_type ON custom_resource_object.custom_resource_type_id = custom_resource_type.id 
WHERE custom_resource_object.factory_station_id = {MySQLHelper.ConvertDecimalToSql(drv["ID"].ToString())} OR custom_resource_object.parent_factory_station_id = {MySQLHelper.ConvertDecimalToSql(drv["ID"].ToString())} ORDER BY custom_resource_object.factory_station_id,custom_resource_object.fname,custom_resource_type.range_type,custom_resource_type.id ");
                if (dtAR == null)
                {
                    MessageBox.Show("查询数据报错！");
                    return;
                }


                // 为DataTable添加对应的列
                dtAR.Columns.Add("IsSelected", typeof(bool));
                dtAR.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列



                ResourceBindingSource.DataSource = dtAR;
                dgResource.DataSource = ResourceBindingSource;

                dgResource.Columns["id"].HeaderText = "ID";
                dgResource.Columns["factory_station_id"].HeaderText = "站点ID";
                dgResource.Columns["fname"].HeaderText = "企业或园区名称";
                dgResource.Columns["type_name"].HeaderText = "资源类型";
                dgResource.Columns["parent_factory_station_id"].HeaderText = "上级园区ID";
                dgResource.Columns["custom_no"].HeaderText = "户号";
                dgResource.Columns["custom_resource_type_id"].Visible = false;
                dgResource.Columns["deleted"].Visible = false;
                dgResource.Columns["push_type"].Visible = false;
                dgResource.Columns["range_type"].Visible = false;
                dgResource.Columns["PtDate"].Visible = false;
                dgResource.Columns["WhDate"].Visible = false;
                dgResource.AutoResizeColumns();
                lbResourceCount.Text = dtAR.Rows.Count.ToString();
                dgResource.CellContentClick += dgResource_CellContentClick;
            }

        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,`site_name`,pkey,parent_pkey FROM site_15min WHERE `site_name` LIKE '%{txtSiteName.Text}%'");
            if (dtA == null || dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;

            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            SiteBindingSource.DataSource = dtA;
            dgSite.DataSource = SiteBindingSource;

            dgSite.Columns["id"].HeaderText = "ID";
            dgSite.Columns["site_name"].HeaderText = "名称";
            dgSite.Columns["pkey"].HeaderText = "数元平台站点ID";
            dgSite.Columns["parent_pkey"].HeaderText = "数元上级节点ID";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dgSite_CellContentClick;



            if (!dgDevice.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn();
                checkBoxColumn2.HeaderText = "选中";
                checkBoxColumn2.Name = "IsSelected";
                checkBoxColumn2.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgDevice.Columns.Add(checkBoxColumn2);
            }


            // 设置不允许新增行
            dgDevice.AllowUserToAddRows = false;

            dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

            //dgDevice.ContextMenuStrip = contextMenuStrip1;

            if (!dgResource.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgResource.Columns.Add(checkBoxColumn);
            }

            if (!dgResource.Columns.Contains("push_type"))
            {
                DataGridViewComboBoxColumn pushTypeColumn = new DataGridViewComboBoxColumn();
                pushTypeColumn.Name = "push_type";
                pushTypeColumn.DataPropertyName = "push_type";
                pushTypeColumn.HeaderText = "推送规则";
                pushTypeColumn.ValueMember = "VALUE";
                pushTypeColumn.DisplayMember = "TEXT";
                pushTypeColumn.DataSource = (cbxPushType.DataSource as DataTable).Copy();
                dgResource.Columns.Add(pushTypeColumn);
            }

            // 设置不允许新增行
            dgResource.AllowUserToAddRows = false;

            dgResource.AllowUserToDeleteRows = false; // 禁止删除行

            txtCustomNo.Text = string.Empty;
            if (DeviceBindingSource.DataSource != null)
            {
                (DeviceBindingSource.DataSource as DataTable).Rows.Clear();
            }
            if (ResourceBindingSource.DataSource != null)
            {
                (ResourceBindingSource.DataSource as DataTable).Rows.Clear();
            }
        }

        private async void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgSite.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgSite.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = SiteBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }
                    DataTable dtResourceType = new DataTable();
                    dtResourceType.Columns.Add("VALUE", typeof(string));
                    dtResourceType.Columns.Add("TEXT", typeof(string));
                    dtResourceType.Rows.Add(new object[] { "", "" });
                    //查询分类
                    var dtResourceTypeData = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,type_name FROM custom_resource_type WHERE factory_station_id is null or factory_station_id={MySQLHelper.ConvertDecimalToSql(drv["pkey"].ToString())} order by range_type,id");
                    foreach (DataRow drType in dtResourceTypeData.Rows)
                    {
                        dtResourceType.Rows.Add(new object[] { drType["id"].ToString(), drType["type_name"].ToString() });
                    }
                    this.cbxResourceType.ValueMember = "VALUE";
                    this.cbxResourceType.DisplayMember = "TEXT";
                    this.cbxResourceType.DataSource = dtResourceType;


                    var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID FROM  dev_powersystemresource where (PATHID like '\\\\{drv["pkey"]}%' OR ID={drv["pkey"]}) AND CLASSNAME IN( 'FactoryStation','Filiale' ) order by PATHID");
                    if (dtA.Rows.Count == 0)
                    {
                        MessageBox.Show("没有查询到相关数据");
                        return;
                    }
                    // 为DataTable添加对应的列
                    dtA.Columns.Add("IsSelected", typeof(bool));
                    dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                    DeviceBindingSource.DataSource = dtA;
                    dgDevice.DataSource = DeviceBindingSource;

                    dgDevice.Columns["ID"].HeaderText = "ID";
                    dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
                    dgDevice.Columns["NAME"].HeaderText = "名称";
                    dgDevice.Columns["PATHID"].HeaderText = "路径";
                    dgDevice.AutoResizeColumns();
                    lbCount.Text = dtA.Rows.Count.ToString();

                    dgDevice.CellContentClick += dgDevice_CellContentClick;
                }
            }

        }

        private async void dgDevice_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgDevice.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgDevice.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgDevice.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = DeviceBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }
                    {
                        var dtAR = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"
SELECT
	custom_resource_object.id,
	custom_resource_object.factory_station_id,
	custom_resource_object.fname,
	custom_resource_type.type_name,
	custom_resource_object.parent_factory_station_id,
	custom_resource_object.custom_no,
	custom_resource_object.range_type,
	custom_resource_object.custom_resource_type_id,
	custom_resource_object.deleted,
	custom_resource_object.push_type,
	(
SELECT REPLACE
	( CAST( update_day AS DATE ), '-', '' ) 
FROM
	custom_object_value_type_time 
WHERE
	custom_object_value_type_time.custom_resource_object_id = custom_resource_object.id 
	AND custom_object_value_type_time.data_value_type = 0 
	) AS PtDate,
	(
SELECT REPLACE
	( CAST( update_day AS DATE ), '-', '' ) 
FROM
	custom_object_value_type_time 
WHERE
	custom_object_value_type_time.custom_resource_object_id = custom_resource_object.id 
	AND custom_object_value_type_time.data_value_type = 1 
	) AS WhDate 
FROM
	custom_resource_object
	LEFT JOIN custom_resource_type ON custom_resource_object.custom_resource_type_id = custom_resource_type.id 
WHERE custom_resource_object.factory_station_id = {MySQLHelper.ConvertDecimalToSql(drv["ID"].ToString())} OR custom_resource_object.parent_factory_station_id = {MySQLHelper.ConvertDecimalToSql(drv["ID"].ToString())} ORDER BY custom_resource_object.factory_station_id,custom_resource_object.fname,custom_resource_type.range_type,custom_resource_type.id ");
                        if (dtAR == null)
                        {
                            MessageBox.Show("查询数据报错！");
                            return;
                        }


                        // 为DataTable添加对应的列
                        dtAR.Columns.Add("IsSelected", typeof(bool));
                        dtAR.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                       
                        ResourceBindingSource.DataSource = dtAR;
                        dgResource.DataSource = ResourceBindingSource;

                        dgResource.Columns["id"].HeaderText = "ID";
                        dgResource.Columns["factory_station_id"].HeaderText = "站点ID";
                        dgResource.Columns["fname"].HeaderText = "企业或园区名称";
                        dgResource.Columns["type_name"].HeaderText = "资源类型";
                        dgResource.Columns["parent_factory_station_id"].HeaderText = "上级园区ID";
                        dgResource.Columns["custom_no"].HeaderText = "户号";
                        dgResource.Columns["custom_resource_type_id"].Visible = false;
                        dgResource.Columns["deleted"].Visible = false;
                        dgResource.Columns["push_type"].HeaderText = "推送规则";
                        dgResource.Columns["range_type"].Visible = false;
                        dgResource.Columns["PtDate"].Visible = false;
                        dgResource.Columns["WhDate"].Visible = false;
                        //把push_type列显示在最后
                        dgResource.Columns["push_type"].DisplayIndex = dgResource.Columns.Count - 1;

                        dgResource.AutoResizeColumns();
                        lbResourceCount.Text = dtAR.Rows.Count.ToString();
                        dgResource.CellContentClick += dgResource_CellContentClick;
                    }

                }
            }

        }


        private async void dgResource_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgResource.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgResource.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgResource.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = ResourceBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }


                }
            }

        }
        private void txtEndDate_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void tsmAllSelect_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = true;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

        private void tsmAllCancel_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = false;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }



        private void txtParentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                e.Handled = true;
            }
        }
    }
}
